package com.whfc.common.util;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 自定义集合工具
 * @author: xugcheng
 * @version: 1.0
 * @date: 2022-01-20 14:27
 */
public class CollectionUtil {

    /**
     * list转map
     *
     * @param list
     * @return
     */
    public static <T> Map<T, T> list2Map(List<T> list) {
        Map<T, T> map = new HashMap<>(list.size());
        for (T obj : list) {
            map.put(obj, obj);
        }
        return map;
    }

    /**
     * list转map
     *
     * @param list
     * @param keyFunc
     * @return
     */
    public static <T, K> Map<K, T> list2Map(List<T> list, Function<T, K> keyFunc) {
        Map<K, T> map = new HashMap<>(list.size());
        for (T obj : list) {
            K key = keyFunc.apply(obj);
            map.put(key, obj);
        }
        return map;
    }

    /**
     * list转map
     *
     * @param list
     * @param keyFunc
     * @param valFunc
     * @return
     */
    public static <T, K, V> Map<K, V> list2map(List<T> list, Function<T, K> keyFunc, Function<T, V> valFunc) {
        Map<K, V> map = new HashMap<>(list.size());
        for (T obj : list) {
            K key = keyFunc.apply(obj);
            V val = valFunc.apply(obj);
            map.put(key, val);
        }
        return map;
    }

    /**
     * 列表分组
     *
     * @param list
     * @param keyFunc
     * @param <T>
     * @param <K>
     * @return
     */
    public static <T, K> Map<K, List<T>> groupBy(List<T> list, Function<T, K> keyFunc) {
        return list.stream().collect(Collectors.groupingBy(keyFunc));
    }

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        Map<Integer, Integer> map = list2Map(list, x -> x * x);
        System.out.println(map);
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

        List<String> strArr = Arrays.asList("x", "xx", "xxx", "a", "aa", "c");
        Map<Integer, List<String>> m = groupBy(strArr, x -> x.length());
        System.out.println(m);
        for (Map.Entry<Integer, List<String>> entry : m.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}
